<template>
  <div class="panel-tab__content">
    <el-button size="small" @click="isDialog">
      点击选择
    </el-button>
    <!--字段列表-->
    <div class="element-property list-property">
      <el-table :data="fileTable" size="mini" max-height="240" border fit>
        <el-table-column prop="processName" label="流程名称">
          <template slot-scope="scope">
            <el-button size="mini" type="text" style="color: #448EF7" @click="getInfo(scope.row,0,2)"
                       v-if="isId !== null"
            >{{ scope.row.processName }}
            </el-button>
            <span v-else
            >{{ scope.row.processName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="processNo" label="流程编号"></el-table-column>
        <el-table-column label="操作" width="90px"
                         v-if="this.$route.params.type === 1 || this.$route.params.type == '1'"
        >
          <template slot-scope="{ row, $index }">
            <el-button size="mini" type="text" style="color: #448EF7" @click="getInfo(row,1,1)"
                       v-if="isId !== null"
            >编辑
            </el-button>
            <el-button size="mini" type="text" style="color: #448EF7" @click="removeAttributes(row, $index)">移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
<!--    <el-form size="mini" @submit.native.prevent ref="ruleForm">-->
<!--      <el-form-item label="系统名称">-->
<!--        <el-input type="textarea" v-model="systemName" clearable placeholder="请输入系统名称"-->
<!--                  @change="saveAttribute('systemName',systemName)"-->
<!--                  :disabled="this.$route.params.type !== 1 && this.$route.params.type !== '1'"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="系统地址">-->
<!--        <el-input type="textarea" v-model="sysUrl" clearable placeholder="请输入系统地址"-->
<!--                  @change="saveAttribute('sysUrl',sysUrl)"-->
<!--                  :disabled="this.$route.params.type !== 1 && this.$route.params.type !== '1'"-->
<!--        />-->
<!--      </el-form-item>-->
<!--    </el-form>-->

    <el-dialog title="关联子流程" :visible.sync="correlationBaseOpen" append-to-body width="70%">
      <choose-process @checkData="checkData"></choose-process>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="deptSubmitForm">确 定</el-button>
        <el-button size="small" @click="deptCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import ChooseProcess from '@/plugins/package/tree/chooseProcess'

export default {
  name: 'CorrelationBaseInfo',
  components: {
    ChooseProcess
  },
  props: {
    id: String,
    businessObject: Object,
    type: String,
    idEditDisabled: {
      type: Boolean,
      default: true
    }
  },
  inject: {
    prefix: 'prefix',
    width: 'width'
  },
  data() {
    return {
      systemName: '',
      sysUrl: '',
      correlationBaseOpen: false,
      elementBaseInfo: {},
      propertyForm: {
        correlation: ''
      },
      editingPropertyIndex: -1,
      bpmnElementPropertyList: [],
      otherExtensionList: [],
      checkDataValue: [],
      fileTable: [],
      isId: ''
    }
  },
  watch: {
    businessObject: {
      immediate: true,
      handler: function(val) {
        if (val) {
          this.$nextTick(() => this.resetBaseInfo())
        }
      }
    }
  },
  methods: {
    resetBaseInfo() {
      this.isId = this.$route.params.id
      console.log('关联流程监听', this.isId)
      this.fileTable = []
      this.bpmnElement = window?.bpmnInstances?.bpmnElement
      this.elementBaseInfo = JSON.parse(JSON.stringify(this.bpmnElement.businessObject))
      this.bpmnElementProperties =
        this.bpmnElement.businessObject?.extensionElements?.values?.filter(ex => {
          if (ex.$type !== `${this.prefix}:Properties`) {
            this.otherExtensionList.push(ex)
          }
          return ex.$type === `${this.prefix}:Properties`
        }) ?? []
      // 保存所有的 扩展属性字段
      this.bpmnElementPropertyList = this.bpmnElementProperties.reduce((pre, current) => pre.concat(current.values), [])
      this.elementPropertyList = JSON.parse(JSON.stringify(this.bpmnElementPropertyList ?? []))
      for (let i = 0; i < this.elementPropertyList.length; i++) {
        let key = this.elementPropertyList[i].name
        if (key === 'correlation') {
          this.fileTable = JSON.parse(this.elementPropertyList[i].value)
        }
        if (key === 'systemName') {
          console.log('this.elementPropertyList[i]', this.elementPropertyList[i])
          this.systemName = this.elementPropertyList[i].value
        }
        if (key === 'sysUrl') {
          this.sysUrl = this.elementPropertyList[i].value
        }
      }
    },
    // 保存拓展字段
    saveAttribute(name, value) {
      // 判断当前属性是否存在
      this.elementPropertyList = JSON.parse(JSON.stringify(this.bpmnElementPropertyList ?? []))
      let index = -1
      for (let i = 0; i < this.elementPropertyList.length; i++) {
        let key = this.elementPropertyList[i].name
        if (name === 'correlation' && key === 'correlation') {
          index = i
        }
        if (name === 'systemName' && key === 'systemName') {
          index = i
        }
        if (name === 'sysUrl' && key === 'sysUrl') {
          index = i
        }
      }
      if (index !== -1) {
        window.bpmnInstances.modeling.updateModdleProperties(this.bpmnElement, this.bpmnElementPropertyList[index], {
          name,
          value
        })
      } else {
        // 新建属性字段
        const newPropertyObject = window.bpmnInstances.moddle.create(`${this.prefix}:Property`, { name, value })
        // 新建一个属性字段的保存列表
        const propertiesObject = window.bpmnInstances.moddle.create(`${this.prefix}:Properties`, {
          values: this.bpmnElementPropertyList.concat([newPropertyObject])
        })
        this.updateElementExtensions(propertiesObject)
      }
    },
    updateElementExtensions(properties) {
      const extensions = window.bpmnInstances.moddle.create('bpmn:ExtensionElements', {
        values: this.otherExtensionList.concat([properties])
      })
      console.log('this.bpmnElement', this.bpmnElement)
      window.bpmnInstances.modeling.updateProperties(this.bpmnElement, {
        extensionElements: extensions
      })
    },
    // 弹出显示
    isDialog() {
      this.correlationBaseOpen = true
    },
    // 确认
    deptSubmitForm() {
      this.correlationBaseOpen = false
      let data = this.checkDataValue

      for (let i = 0; i < data.length; i++) {
        let bo = true
        if (this.fileTable.length !== 0) {
          for (let b = 0; b < this.fileTable.length; b++) {
            if (this.fileTable[b].processId === data[i].processId) {
              bo = false
            }
          }
        }
        if (bo) {
          this.fileTable.push({
            processId: data[i].processId,
            processNo: data[i].processNo,
            processName: data[i].processName
          })
        }
      }

      this.saveAttribute('correlation', JSON.stringify(this.fileTable))
      // 只在预览 或者 编辑的情况下
      if (this.$route.params.id !== undefined && this.$route.params.id !== null && this.$route.params.id !== '') {
        this.$emit('update', true)
      }
    },
    // 取消
    deptCancel() {
      this.correlationBaseOpen = false
    },
    // 子页面回传参数
    checkData(data) {
      console.log('子页面回传参数', data)
      this.checkDataValue = []
      for (let i = 0; i < data.length; i++) {
        this.checkDataValue.push({
          processId: data[i].processId,
          processNo: data[i].processNo,
          processName: data[i].processName
        })
      }

    },
    // 移除文件
    removeAttributes(attr, index) {
      this.$confirm('确定移除当前流程提示么？', '提示', {
        confirmButtonText: '确 认',
        cancelButtonText: '取 消'
      })
        .then(() => {
          this.fileTable.splice(index, 1)
          this.saveAttribute('correlation', JSON.stringify(this.fileTable))
          // 只在预览 或者 编辑的情况下
          if (this.$route.params.id !== undefined && this.$route.params.id !== null && this.$route.params.id !== '') {
            this.$emit('update', true)
          }
        })
        .catch(() => console.info('操作取消'))
    },
    // 新增或者编辑 打开新的弹窗
    getInfo(row, type, routeType) {
      let id = row.processId
      console.log('row.processId', row.processId)
      let businessTypeId = row.businessTypeId
      this.designerOpen = true
      let query = {}
      if (id !== undefined && id !== '' && id !== null) {
        query = { id: id, parentId: 0, type: type }
      } else {
        query = { id: id, parentId: 0, type: type }
      }
      if (routeType === 0) {
        this.$router.push({ name: 'AddModel', params: query })
      } else if (routeType === 1) {
        console.log('进入')
        this.$router.push({ name: 'UpdateModel', params: query })
      } else {
        this.$router.push({ name: 'ViewModel', params: query })
      }
    }
  },
  beforeDestroy() {
    this.bpmnElement = null
  }
}
</script>
